import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';

import 'package:flutter_rider/app.dart';
import 'package:flutter_rider/event/action_home_index_event.dart';
import 'package:flutter_rider/event/click_select_car_event.dart';
import 'package:flutter_rider/event/show_pop_select_car_event.dart';
import 'package:flutter_rider/kit/app_update_kit.dart';
import 'package:flutter_rider/kit/mqtt_kit.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_rider/main/widgets/ext/u_layout.dart';
import 'package:flutter_rider/module/mine/page/mine_page.dart';
import 'package:flutter_rider/module/mine/provider/mine_provider.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_rider/utils/tip.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_rider/event/change_stations_event.dart';
import 'package:flutter_rider/generated/r.dart';
import 'package:flutter_rider/kit/loc_kit.dart';
import 'package:flutter_rider/utils/alib.dart';
import 'package:flutter_rider/module/car/page/manage_page.dart';
import 'package:flutter_rider/module/home/page/home_page.dart';
import 'package:flutter_rider/module/task/page/task_page.dart';
import 'package:flutter_rider/module/waybill/page/billway_page.dart';
import 'package:flutter_rider/main/widgets/pop/pop_new_stations_list.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_rider/event/click_close_stations_event.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';

class MainPage extends ConsumerStatefulWidget {
  @override
  ConsumerState createState() {
    return MainPageState();
  }
}

class MainPageState extends ConsumerState<MainPage> {
  static dynamic _loginInfo = {};
  static const _loginKey = "login_info";
  final List _tabs = ["运单", "任务", "工作台", "车辆", "我的"];
  final _images = [
    R.image_main_tab_billway,
    R.image_main_tab_task,
    R.image_main_tab_home,
    R.image_main_tab_car,
    R.image_main_tab_mine
  ];
  var _index = 2;
  var _lastBackTime = 0;
  late StreamSubscription _eventFn3;
  late StreamSubscription _eventFn4;
  late StreamSubscription _eventFn5;

  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  late StreamSubscription _eventSelectCar;
  bool showNav = true;
  Timer? _refreshTimer;

  @override
  void initState() {
    super.initState();

    LocKit.instance.requestPermission();
    MqttKit.instance.connect();
    AppUpdateKit.instance.check(context, false);
    _eventFn3 = eventBus.on<ChangeStationsEvent>().listen((event) {
      Navigator.of(context).pop();
    });
    // _eventFn4 = eventBus.on<ClickCloseStationsEvent>().listen((event) {
    //   setState(() {
    //     showNav = true;
    //   });
    // });

    _eventFn4 = eventBus.on<ShowPopSelectCarEvent>().listen((event) {
      setState(() {
        showNav = !event.isShowPopSelectCar;
      });
    });
    _eventSelectCar = eventBus.on<ClickSelectCarEvent>().listen((event) {
      // OpenUtils.pop4(context, PopNewStationsList(event.lat,event.lng,event.car_no,event.mode,event.status,event.car_id,event.lx,event.type));

      // showBottomSheet(
      //   context: context,
      //   builder: (_) => StatefulBuilder(builder: (context, state) {
      //     return PopNewStationsList(event.lat, event.lng, event.car_no,
      //         event.mode, event.status, event.car_id, event.lx, event.type);
      //   }),
      // );

      _scaffoldKey.currentState?.showBottomSheet(
        (context) => StatefulBuilder(builder: (context, state) {
          return PopNewStationsList(event.lat, event.lng, event.car_no,
              event.mode, event.status, event.car_id, event.lx, event.type);
        }),
        backgroundColor: Colors.transparent,
      );
    });

    _eventFn5 = eventBus.on<ActionHomeIndexEvent>().listen((event) {
      setState(() {
        _index = event.index;
      });
      initButton(_index);
    });
  }

  @override
  void dispose() {
    super.dispose();
    _eventFn3.cancel();
    _eventFn4.cancel();
    _eventFn5.cancel();
    _eventSelectCar.cancel();
  }

  @override
  Widget build(BuildContext context) {
    Widget child;
    if (App.isLandscape) {
      child = Row(
        children: [
          Container(
            decoration:
                const BoxDecoration(color: UIColor.color_content, boxShadow: [
              BoxShadow(
                  color: Colors.black12, offset: Offset(1, 0), blurRadius: 1),
            ]),
            width: 66.rpx + MediaQuery.of(context).padding.left,
            padding: EdgeInsets.only(
                left: MediaQuery.of(context).padding.left,
                top: MediaQuery.of(context).padding.top),
            child: Column(
              children: _tabs
                  .asMap()
                  .keys
                  .map((e) => _renderVerticalTabItem(e))
                  .toList(),
            ),
          ),
          _renderContent(),
          SizedBox(width: MediaQuery.of(context).padding.right),
        ],
      );
    } else {
      child = Column(
        children: [
          _renderContent(),
        ],
      );
    }

    return WillPopScope(
      child: Scaffold(
              resizeToAvoidBottomInset: false,
              key: _scaffoldKey,
              body: child,
              floatingActionButton: showNav && !App.isLandscape
                  ? Container(
                      height: 72.rpx,
                      width: 72.rpx,
                      margin: EdgeInsets.only(top: 30.rpx),
                      padding: const EdgeInsets.all(8),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(40),
                        image: const DecorationImage(
                          image: AssetImage('assets/image/poi/line_circle.png'),
                          fit: BoxFit.fill, // 完全填充
                        ),
                      ),
                      //工作台按钮
                      child: FloatingActionButton(
                        child: SvgPicture.asset(R.image_main_tab_home,
                            color: _index == 2
                                ? UIColor.color_content
                                : const Color(0xFFD2E0EE),
                            width: 39.rpx,
                            height: 39.rpx),
                        backgroundColor: _index == 2
                            ? UIColor.color_primary
                            : const Color(0xffF3F3F3),
                        elevation: 0,
                        onPressed: () {
                          Alib.hideKeyboard(context);
                          setState(() {
                            _index = 2;
                          });
                          initButton(_index);
                        },
                      ),
                    )
                  : 0.wspace,
              floatingActionButtonLocation:
                  FloatingActionButtonLocation.centerDocked,
              bottomNavigationBar: showNav && !App.isLandscape
                  ? BottomNavigationBar(
                      currentIndex: _index,
                      unselectedItemColor:
                          const Color(0xffD2E0EE), //主要用于设置字体未选中时颜色
                      selectedItemColor: UIColor.color_primary, //主要用于设置字体选中时颜色
                      selectedFontSize: 10.rpx,
                      unselectedFontSize: 10.rpx,
                      backgroundColor: UIColor.color_content,
                      onTap: (int index) {
                        setState(() {
                          _index = index;
                        });
                        initButton(index);
                      },
                      type: BottomNavigationBarType.fixed,
                      items: _tabs
                          .asMap()
                          .keys
                          .map((e) => _renderHorizontalTabItem(e))
                          .toList(),
                    )
                  : 0.wspace)
          .onTap(() {
        Alib.hideKeyboard(context);
      }),
      onWillPop: () async {
        int now = DateTime.now().millisecondsSinceEpoch;
        if (now - _lastBackTime < 2000) {
          return true;
        } else {
          Tip.show("再按一次退出");
          _lastBackTime = now;
          return false;
        }
      },
    );
  }

  Widget _renderVerticalTabItem(int index) {
    var color =
        _index == index ? UIColor.color_primary : const Color(0xff5E5E5E);
    return Expanded(
      child: GestureDetector(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            SvgPicture.asset(_images[index],
                color: color, width: 24.rpx, height: 24.rpx),
            2.hspace,
            UText.get(_tabs[index], color, 10.rpx),
          ],
        ),
        behavior: HitTestBehavior.opaque,
        onTap: () async {
          Alib.hideKeyboard(context);
          setState(() {
            _index = index;
          });
          initButton(index);
        },
      ),
    );
  }

  Widget _renderContent() {
    return Expanded(
      child: IndexedStack(
        index: _index,
        children: [
          _index == 0 ? BillWayPage() : 0.wspace,
          _index == 1 ? TaskPage() : 0.wspace,
          _index == 2 ? HomePage() : 0.wspace,
          _index == 3 ? ManagePage() : 0.wspace,
          _index == 4 ? MinePage() : 0.wspace,
        ],
      ),
    );
  }

  BottomNavigationBarItem _renderHorizontalTabItem(int index) {
    var color =
        _index == index ? UIColor.color_primary : const Color(0xFFBCC4D0);
    return BottomNavigationBarItem(
      label: _tabs[index],
      icon: SvgPicture.asset(_images[index],
          color: color, width: 24.rpx, height: 24.rpx),
    );
  }

  initButton(index) async {
    var _sp = await SharedPreferences.getInstance();
    _sp.setBool("_showDispatch", false);
    _sp.setBool("_showUndistributed", false);
    _sp.setBool("_showCopyWaybillOrder", false);
    _sp.setBool("_showCompleteWaybillOrder", false);
    ref.read(isShowOperatorProvider.state).state = false;
    if (_sp.containsKey(_loginKey)) {
      _loginInfo = jsonDecode(_sp.getString(_loginKey) ?? "");
      _loginInfo["menu"].forEach((element) {
        // 判断是否包含
        if (element["name"].contains(_tabs[index])) {
          element["menu"].forEach((data) {
            if (data["name"] == "调车") {
              _sp.setBool("_showDispatch", true);
            }
            if (data["name"] == "未分配") {
              _sp.setBool("_showUndistributed", true);
            }
            if (data["name"] == "复制运单") {
              _sp.setBool("_showCopyWaybillOrder", true);
            }
            if (data["name"] == "完善运单") {
              _sp.setBool("_showCompleteWaybillOrder", true);
            }

            if (data["name"] == "查看操作员位置") {
              ref.read(isShowOperatorProvider.state).state = true;
            }
          });
        }
      });
    }
  }
}
